//
//  DiscountViewController.m
//  WhereToTravel
//
//  Created by dlios on 15/10/14.
//  Copyright © 2015年 zhoushengmin. All rights reserved.
//

#import "DiscountViewController.h"
#import "KnockDiscountModel.h"
#import "WebViewController.h"
#import "KnockDiscountCollectionViewCell.h"

@interface DiscountViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *discountArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation DiscountViewController

// 视图的出现将tabbar隐藏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(night) name:@"night" object:nil];
        self.discountArr = [NSMutableArray array];
        [self createData];
    }
    return self;
}

#pragma mark 抢折扣数据解析
- (void)createData {
    self.page++;
    NSString *strUrl = [NSString stringWithFormat:@"http://open.qyer.com/lastminute/app_lastminute_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&continent_id=0&count=20&country_id=0&departure=&is_show_pay=1&is_show_supplier=1&lat=38.8826676005059&lon=121.5397836874259&max_id=0&oauth_token=3ccf6be2c77dee4d33e6d6a5eb878fc7&page=%ld&page_size=20&product_type=0&times=&track_app_channel=App%%2520Store&track_app_version=6.5.5&track_device_info=iPhone7%%2C2&track_deviceid=5B302CA5-E537-4B10-955D-520F4C91BAFE&track_os=ios%%25208.1.2&track_user_id=6654242&v=1%%20",self.page];
    strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [ZSMAFNetWork geturl:strUrl body:nil result:ZSMJSON headerFile:nil success:^(id result) {
        NSMutableDictionary *strDic = result;
        NSMutableDictionary *secDic = strDic[@"data"];
        NSMutableArray *strArr= secDic[@"lastminutes"];
        for (NSMutableDictionary *dic in strArr) {
            KnockDiscountModel *knockDiscountModel = [[KnockDiscountModel alloc] init];
            [knockDiscountModel setValuesForKeysWithDictionary:dic];
            [self.discountArr addObject:knockDiscountModel];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.footer endRefreshing];
        self.hud.hidden = YES;
    } failure:^(NSError *error) {
        NSLog(@"错误是:%@",error);
        
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100 * WIDTH, 30 * HEIGHT)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = @"抢折扣";
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = self.titleLabel;
    [self createCollectionView];
    
    // 左上角返回图标
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"返回"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftAction:)];
}

// 返回
- (void)leftAction:(UIBarButtonItem *)barButton {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark collectionView的创建
- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(180 * WIDTH, 220 * HEIGHT);
    flowLayout.minimumInteritemSpacing = 0 ;
    flowLayout.minimumLineSpacing = 40 * HEIGHT;
    //边角
    flowLayout.sectionInset = UIEdgeInsetsMake(5 * WIDTH, 5 * HEIGHT,5 * WIDTH, 5 * HEIGHT);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 554) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    self.hud = [MBProgressHUD showHUDAddedTo:self.collectionView animated:YES];
    [self.hud hide:YES afterDelay:2];
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
        
    }];
    [self.collectionView registerClass:[KnockDiscountCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self createMJRefresh];
}

// 空白页占位图
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, self.view.bounds.size.height/2, WIDTH*375, 30)];
    label.text = @"! 网速不给力";
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor redColor];
    return label;
}


- (void)createMJRefresh {
    // 上拉加载
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(createData)];
}

#pragma mark collectionView的数据处理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.discountArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KnockDiscountCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    KnockDiscountModel *knockDiscountModel = self.discountArr[indexPath.row];
    [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:knockDiscountModel.pic] placeholderImage:[UIImage imageNamed:@"占位图"]];
    if (self.discountArr.count > indexPath.row) {
        cell.upLabel.text = knockDiscountModel.title;
        NSString *strTime = [NSString stringWithFormat:@"时间:%@",knockDiscountModel.departureTime];
        cell.mistLabel.text = strTime;
        if ([knockDiscountModel.lastminute_des isEqualToString:@""]) {
            cell.downLeftLabel.text = @"";
        }
        else {
            cell.downLeftLabel.text = knockDiscountModel.lastminute_des;
        }
        NSString *strString = knockDiscountModel.price;
        if (strString.length == 15) {
            NSString *str = [strString substringWithRange:NSMakeRange(4, 4)];
            str = [NSString stringWithFormat:@"%@元起",str];
            cell.downRightLabel.text = str;
        }
        else if (strString.length == 16){
            
            NSString *str = [strString substringWithRange:NSMakeRange(4, 5)];
            str = [NSString stringWithFormat:@"%@元起",str];
            cell.downRightLabel.text = str;
        }
        else if (strString.length == 14) {
            NSString *str = [strString substringWithRange:NSMakeRange(4, 3)];
            str = [NSString stringWithFormat:@"%@元起",str];
            cell.downRightLabel.text = str;
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    WebViewController *webVC = [[WebViewController alloc] init];
    [self.navigationController pushViewController:webVC animated:YES];
    KnockDiscountModel *knockDiscountModel = self.discountArr[indexPath.row];
    webVC.url = knockDiscountModel.url;
}

- (void)night {
    if ([SingletonNight shareSingletonNight].isSelete == YES) {
        self.collectionView.backgroundColor = [UIColor blackColor];
        self.titleLabel.textColor = [UIColor blackColor];
    }
    else {
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.titleLabel.textColor = [UIColor whiteColor];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
